/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ro.futurefeed.repository;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import ro.futurefeed.model.Feed;
import ro.futurefeed.api.FeedStatus;
import ro.futurefeed.model.User;

/**
 *
 * @author Alex
 */
@Repository
@Transactional
public class FeedRepositoryImpl implements FeedRepository {
    
    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public Feed save(Feed feed) {
        entityManager.persist(feed);
        entityManager.flush();
        return feed;
    }

    @Override
    public Feed update(Feed feed) {
        feed = entityManager.merge(feed);
        entityManager.flush();
        return feed;
    }

    @Override
    @Transactional(readOnly=true)
    public Feed findById(long id) {
        Feed singleResult;
        
        try {
            Query query = entityManager.createQuery("select f from Feed f where f.id = :id");
            query.setParameter("id", id);
            singleResult = (Feed) (query.getSingleResult());
        } catch(NoResultException nre) {
            singleResult = null;
        }
        
        return singleResult;
    }

    @Override
    @Transactional(readOnly=true)
    public List<Feed> getUserFeeds(User user) {
        Query query = entityManager.createQuery("select f from Feed f where f.userKey = :userKey "
                + "order by f.dateGMT desc");
        query.setParameter("userKey", user.getId());
        
        return (List<Feed>) query.getResultList();
    }

    @Override
    public Feed delete(Feed feed) {
        feed = entityManager.merge(feed);
        entityManager.remove(feed);
        entityManager.flush();
        return feed;
    }

    @Override
    @Transactional(readOnly=true)
    public List<Feed> getFeeds(String toDate, FeedStatus status) {
        Query query = entityManager.createQuery("select f from Feed f where f.status = :status "
                + "and f.dateGMT <= :toDate order by f.dateGMT desc");
        query.setParameter("status", status);
        query.setParameter("toDate", toDate);
        
        return (List<Feed>) query.getResultList();
    }
    
}
